package com.star.cat.common.parse;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import com.alibaba.fastjson.JSON;

/**
 * 默认返回结果解析器
 * @author liguangcai
 * @date 2018/08/30 08:50
 */
public class DefaultResultParse implements ResultParse{

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public Object parse(String value, Type returnType, Class<?>... raws) {
		if (returnType instanceof ParameterizedType) { // 返回值是 参数化类型(泛型)
			ParameterizedType parameterizedType = (ParameterizedType) returnType;
			Type rawType = parameterizedType.getRawType();
			if (((Class)rawType).isAssignableFrom(List.class)) {
				return JSON.parseArray(value, (Class) parameterizedType.getActualTypeArguments()[0]);
			}
		}else if (raws == null || raws.length == 0) {
			return JSON.parseObject(value, returnType);
		}else {
			return JSON.parseObject(value, raws[0]);
		}
		return null;
	}

}
